package com.dj.mingkong.admin.biz.service.music.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.admin.biz.controller.music.vo.request.TypeAddVo;
import com.dj.mingkong.admin.biz.controller.music.vo.request.TypeQueryVo;
import com.dj.mingkong.admin.biz.controller.music.vo.request.TypeUpdateVo;
import com.dj.mingkong.admin.biz.controller.music.vo.response.TypeVo;
import com.dj.mingkong.admin.biz.repository.database.music.TypeRepository;
import com.dj.mingkong.admin.biz.service.music.TypeService;
import com.dj.mingkong.common.constant.CommonConstants;
import com.dj.mingkong.common.enums.StatusEnum;
import com.dj.mingkong.common.exception.ValidateException;
import com.dj.mingkong.common.infrastructure.base.dto.delete.DeleteVo;
import com.dj.mingkong.common.infrastructure.base.dto.page.PageVo;
import com.dj.mingkong.common.infrastructure.eo.database.music.TypeEo;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.common.util.SmartBeanCopy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 音乐类型服务实现类
 *
 * @author zenglonghui
 * @date: 2022/7/20 16:39
 */
@Slf4j
@Service("typeService")
public class TypeServiceImpl implements TypeService {
    @Resource
    private TypeRepository typeRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(TypeAddVo addVo) {
        if (!CommonConstants.DEFAULT_ID.equals(addVo.getParentId())) {
            final TypeEo typeEo = typeRepository.getById(addVo.getParentId());
            AssertUtils.isNotNull(typeEo, "parentId invalid");
        }
        checkTypeName(addVo.getParentId(), addVo.getName());
        final TypeEo typeEo = SmartBeanCopy.copy(addVo, TypeEo.class);
        typeRepository.save(typeEo);
    }

    private void checkTypeName(Long parentId, String name) {
        if (typeRepository.existByParentIdAndName(parentId, name)) {
            throw new ValidateException("typeName already exist");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateById(TypeUpdateVo updateVo) {
        final TypeEo typeEo = typeRepository.getById(updateVo.getId());
        AssertUtils.isNotNull(typeEo, "TypeVo invalid");
        if (!typeEo.getName().equals(updateVo.getName())) {
            checkTypeName(typeEo.getParentId(), updateVo.getName());
        }
        final TypeEo eo = SmartBeanCopy.copy(updateVo, TypeEo.class);
        typeRepository.updateById(eo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(DeleteVo deleteVo) {
        typeRepository.deleteById(deleteVo.getId());
    }

    @Override
    public PageVo<TypeVo> pageByVo(TypeQueryVo queryVo) {
        final TypeEo typeEo = SmartBeanCopy.copy(queryVo, TypeEo.class);
        final Page<TypeEo> eoPage = typeRepository.listPage(typeEo,
                queryVo.getPage(), queryVo.getPageSize());
        return SmartBeanCopy.copyPageVo(eoPage, TypeVo.class);
    }

    @Override
    public List<TypeVo> getParentList() {
        final List<TypeEo> typeEos = typeRepository.listByParentId(CommonConstants.DEFAULT_ID);
        final List<TypeVo> typeVos = SmartBeanCopy.copy(typeEos, TypeVo.class);
        setDisabled(typeVos);
        return typeVos;
    }

    @Override
    public List<TypeVo> listTree() {
        final List<TypeEo> allEos = typeRepository.list();
        if (CollectionUtils.isEmpty(allEos)) {
            return Collections.emptyList();
        }
        final List<TypeVo> allVos = SmartBeanCopy.copy(allEos, TypeVo.class);
        final List<TypeVo> vos = allVos.stream().filter(vo ->
                CommonConstants.DEFAULT_ID.equals(vo.getParentId())).toList();
        setChildren(vos, allVos);
        return vos;
    }

    @Override
    public List<TypeVo> listAll() {
        final List<TypeEo> typeEos = typeRepository.lambdaQuery().orderByAsc(TypeEo::getSort).list();
        final List<TypeVo> typeVos = SmartBeanCopy.copy(typeEos, TypeVo.class);
        setDisabled(typeVos);
        return typeVos;
    }

    private void setDisabled(List<TypeVo> typeVos) {
        if (CollectionUtils.isNotEmpty(typeVos)) {
            typeVos.forEach(vo -> vo.setDisabled(StatusEnum.INVALID.equalsIntVal(vo.getStatus())));
        }
    }

    private void setChildren(List<TypeVo> vos, List<TypeVo> allVos) {
        vos.forEach(vo -> {
            vo.setDisabled(!StatusEnum.VALID.equalsIntVal(vo.getStatus()));
            final List<TypeVo> childrenList = allVos.stream().filter(item ->
                    vo.getId().equals(item.getParentId())).toList();
            if (CollectionUtils.isNotEmpty(childrenList)) {
                vo.setChildren(childrenList);
                setChildren(childrenList, allVos);
            }
        });
    }
}
